package com.system.manager.utils;


import com.system.manager.common.entity.TokenInfo;
import com.system.manager.common.entity.TokenResult;
import com.system.manager.common.helper.IRedisHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author meteor
 */
@Component
public class TokenManager {

    private IRedisHelper redisHelper;

    private static final int DEFAULT_EXPIRE = 60 * 60 * 24 * 30;
    private static final int REFRESH_DEFAULT_EXPIRE = DEFAULT_EXPIRE * 2;

    private static final int ANDROID_DEFAULT_EXPIRE = 60 * 60 * 24 * 30;

    private static final int ANDROID_REFRESH_DEFAULT_EXPIRE = 60 * 60 * 24 * 10 * 30;

    @Autowired
    public void setRedisHelper(IRedisHelper redisHelper) {
        this.redisHelper = redisHelper;
    }

    /**
     * 生成token
     *
     * @param userId
     * @param role
     * @return
     */
    public TokenResult generateToken(Integer userId, Integer role) {

        // 生成新token
        String newToken = UUIDUtils.randomToken();
        String newRefreshToken = UUIDUtils.randomToken();


        redisHelper.set(RedisKey.TOKEN_TO_USER(newToken), TokenInfo.create(newToken, userId,  role), DEFAULT_EXPIRE);
//        redisHelper.set(RedisKey.USER_TOKEN_INFO(userId), newToken, DEFAULT_EXPIRE);

//        redisHelper.set(RedisKey.REFRESH_TOKEN_TO_USER(newRefreshToken), TokenInfo.create(newRefreshToken, userId,  role), REFRESH_DEFAULT_EXPIRE);
//        redisHelper.set(RedisKey.USER_REFRESH_TOKEN_INFO(userId), newRefreshToken, REFRESH_DEFAULT_EXPIRE);
        return new TokenResult(newToken, newRefreshToken);
    }

    /**
     * 根据token获取token信息
     *
     * @param token
     * @return
     */
    public TokenInfo getTokenInfo(String token) {
        System.out.println("当前的token是：" + token);
        TokenInfo tokenInfo = redisHelper.get(RedisKey.TOKEN_TO_USER(token), TokenInfo.class);

        // 如果是web端，则刷新token
        if (tokenInfo != null) {
            // 刷新token过期时间
            System.out.println("进行了时间延期.....");
            redisHelper.expire(RedisKey.TOKEN_TO_USER(token), DEFAULT_EXPIRE);
//            redisHelper.expire(RedisKey.USER_TOKEN_INFO(tokenInfo.getUserId()), DEFAULT_EXPIRE);
        }
        return tokenInfo;
    }

    /**
     * 根据refreshToken获取refreshToken信息
     *
     * @param refreshToken
     * @return
     */
    public TokenInfo getRefreshTokenInfo(String refreshToken) {
        TokenInfo tokenInfo = redisHelper.get(RedisKey.REFRESH_TOKEN_TO_USER(refreshToken), TokenInfo.class);
        return tokenInfo;
    }


}
